package com.mars.boss.weixin.wx.jobs;

import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mars.boss.weixin.wx.utils.WeixinConstant;
import com.mars.boss.weixin.wx.utils.WeixinContext;
import com.mars.common.utils.date.DateUtils;
import com.mzlion.easyokhttp.HttpClient;

/**
 * 定时获取微信AccessToken 每2小时获取一次
 * 
 * @author yhaoquan
 * 
 */
public class RefreshAccessTokenJob extends QuartzJobBean {

	private Logger logger = LoggerFactory.getLogger(getClass());

	private static int repeatRefreshAccessTokenCount = 3;

	@Override
	protected void executeInternal(JobExecutionContext context)
			throws JobExecutionException {
		// 作业开始时间
		long startTime = System.currentTimeMillis();

		WeixinContext.setAccessToken(getAccessToken());

		JobDetail jobDetail = context.getJobDetail();
		logger.info(
				"执行作业【任务描述：{}    任务ID： {}   任务类：{}   下一次执行时间：{}   总共耗时：{}毫秒】",
				jobDetail.getDescription(),
				jobDetail.getKey(),
				jobDetail.getJobClass(),
				(context.getNextFireTime() != null ? DateUtils.formatDate(context.getNextFireTime(), "yyyy-MM-dd HH:mm:ss") : "立即执行"), 
				System.currentTimeMillis() - startTime);
	}

	/**
	 * 获取微信AccessToken
	 * 
	 * @return
	 */
	private String getAccessToken() {
		String at = HttpClient.get(WeixinConstant.ACCESS_TOKEN_URL).execute().asString();
		JSONObject parseObject = JSON.parseObject(at);

		if (null != parseObject.get("access_token")) {
			String accessToken = parseObject.get("access_token").toString();
			logger.info("微信AccessToken刷新成功，Access_Token：{}", accessToken);
			repeatRefreshAccessTokenCount = 3;
			return accessToken;
		} else {
			logger.warn("AccessToken获取失败：{}", at);
			repeatRefreshAccessTokenCount--;
			// 如果获取AccessToken 失败，重复获取3次
			if (repeatRefreshAccessTokenCount > 0) {
				getAccessToken();
			}
		}
		return null;
	}

	public void firstGetAccessToken() {
		logger.info("Spring容器启动执行，首次获取微信AccessToken，保存到上下文");
		WeixinContext.setAccessToken(getAccessToken());
	}

}
